<template>
  <!-- 经销商建设验收查询 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="topFilterRef"
      :list="topFilterInit"
      :cols="3"
      labelWidth="120"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      columnsRef='origin_construct_inquire_index_01'
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" :loading="saveLoading" icon="el-icon-download" @click="exportExcel()">下载</el-button>
      </template>
    </FilterTable>
    <Drawer
      title="建设验收修改"
      :visible.sync="visibleDrawer"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
       >
      <addDialog v-model="initData" @close="dialogClose" />
    </Drawer>
    <Drawer
      title="建设验收明细"
      :visible.sync="visibleDrawerShow"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
       >
      <showDialog v-model="initData" @close="dialogCloseShow" />
    </Drawer>
    <BaseDialog 
      title="创建人选择" 
      width="700px"
      destroyOnClose
      :visible.sync="visiblePersonnel"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}" >
      <personnel-madal  ref="personnelDialog" selectType='single' @close="closePersonnel" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import addDialog from './addDialog'
import showDialog from './showDialog'
import { exportExcelFile } from '@/utils';
import { searchDealerApply ,exportExcel} from '@/api/cms-api/origin/construct/dealer';
import { region } from '@/api/cms-common/region';
import { getRegion, getCommunity } from '@/api/cms-common/dealerdata/index';
import { dealerCommon } from '@/api/cms-api/origin/commonDealerType';		//渠道类型工具类
import personnelMadal from '@/pages/cms-common/user'
import { formatdateByDay } from '@/utils';
import * as types from '@/api/cms-api/origin/construct/dealer/types';

export default {
  mixins: [dictionary,region,dealerCommon],
  components: {
    addDialog,showDialog,personnelMadal
  },
  data() {
    return {
      isSelectColumn: false,
      visibleDrawer: false,
      visibleDrawerShow: false,
      initData: {},
      topFilterInit: this.topFilterInitFun(),
      fetchParams: {}, //参数
      columns: this.creatHeader(),
      saveLoading: false,
      visiblePersonnel: false,  //人员弹窗开关
      userId:"",
      userName:"",
      fetchApi: searchDealerApply //ipa 接口
    };
  },
  mounted() {
    //初始化事业部下拉数据
    this.getDeptData();
    //初始化省份信息
    this.initProvince();

    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: '经销商公司全称', fieldName: 'dealerName', placeholder: '请输入' },
        // { type: 'SELECT', label: '渠道类型', fieldName: 'dealerType', placeholder: '请选择', itemList: this.createDictListRemoveCodes('2538',['25381006']) },
        { type: 'SELECT', label: '渠道类型', fieldName: 'dealerType', placeholder: '请选择', itemList: this.getOriginInfoDealerTypeNoBig() },
        { type: 'RANGE_DATE',  label: '创建日期',  fieldName: 'createdAt',  valueFormat: 'yyyy-MM-dd',    placeholder: '请选择' },
        { type: 'SELECT', label: '事业部', fieldName: 'deptId', placeholder: '请选择',  itemList: [] },
        { type: 'SELECT', label: '经销商级别', fieldName: 'shopLevel', placeholder: '请选择',  itemList: this.createDictList('2540') },
        { type: 'SELECT', label: '建设状态', fieldName: 'buildStatus', placeholder: '请选择',  itemList: this.createDictList('2546') },
        { type: 'SELECT', 
          label: '省份', 
          fieldName: 'provinceId', 
          placeholder: '请选择',  
          itemList: [],
          change: (value) => {
            this.initCity(value)
          },
        },
        { type: 'SELECT', 
          label: '城市', 
          fieldName: 'cityId', 
          placeholder: '请选择',  
          itemList: [],
          change: (value) => {
            this.initTown(value)
          },
        },
        { type: 'SELECT', label: '县区', fieldName: 'districtId', placeholder: '请选择',  itemList: [] },
        // { type: 'SELECT', label: '审批状态', fieldName: 'status', placeholder: '请选择',  itemList: this.createDictListRemoveCodes('2544',['25441005']) },
        { type: 'SELECT', label: '审批状态', fieldName: 'status', placeholder: '请选择',  itemList: this.createDictList('2544') },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'userName',
          placeholder: '请选择',
          initialValue: '',
          readonly:true,
          unitRender: () => {
            return (
                <div>
                    <el-button slot="append" icon="el-icon-search" onClick={() =>this.personnelHandle()}></el-button>
                    <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearPersonnelHandle()}></el-button>
                </div>
            );
          }
        },
        { type: 'SELECT', label: '是否创建临时账号', fieldName: 'isCreateTempAccount', placeholder: '请选择',  itemList: this.createDictList('1004') },
        { type: 'SELECT', label: '是否转经销商', fieldName: 'isChangeDealer', placeholder: '请选择',  itemList: this.createDictList('1004') },
      ];
    },
    //搜索获取数据
    changeHandle(val) {
      if (!val) {
        val = {createdAt:[]}
      }
      if(!val.userName){
        this.userId = '';
      }
      this.fetchParams = Object.assign({
        createdAtStart:val.createdAt[0]||undefined,
        createdAtEnd:val.createdAt[1]||undefined,
        "createdBy":this.userId
      }, val);
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            let editBtn,editBtnEnd;
            if(props.row.status != types.BUILD_STATUS_PASS){
              editBtn = (
                <el-button size="mini" type="text" onClick={() => this.dialogHandle(props.row,'edit')}>
                  编辑
                </el-button>
              );
              editBtnEnd = (<el-divider direction="vertical" />);
            }
            
            return (
              <div>
                {editBtn}
                {editBtnEnd}
                <el-button size="mini" type="text" onClick={() => this.dialogHandleShow(props.row,'show')}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        // { title: '品牌', dataIndex: 'brandId', sorter: true },
        { title: '品牌', dataIndex: 'appId', sorter: true ,
           render: props => {    //编码转大写
           let a = props.row.appId.toUpperCase();
            return <span>{a}</span>;
          }},
        { title: '经销商公司全称', dataIndex: 'dealerName', sorter: true },
        { title: '临时代码', dataIndex: 'dealerCode', sorter: true },
        { title: '审批状态', dataIndex: 'status', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.status, '2544')}</span>;
          }},
        { title: '是否创建临时账号', dataIndex: 'isCreateTempAccount', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.isCreateTempAccount, '1004')}</span>;
          }
        },
        { title: '是否转经销商', dataIndex: 'isChangeDealer', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.isChangeDealer, '1004')}</span>;
          }
        },
        { title: '经销商简称', dataIndex: 'dealerShortname', sorter: true },
        { title: '渠道类型', dataIndex: 'dealerType', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.dealerType, '2538')}</span>;
          }},
        { title: '经销商级别', dataIndex: 'shopLevel', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.shopLevel, '2540')}</span>;
          }
        },
        { title: '建设类型', dataIndex: 'constructType', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.constructType, '2541')}</span>;
          }}, 
        { title: '建设状态', dataIndex: 'buildStatus', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.buildStatus, '2546')}</span>;
          }},
        
        { title: '展厅级别', dataIndex: 'salesLevel', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.salesLevel, '2542')}</span>;
          }},
        { title: '售后级别', dataIndex: 'serviceLevel', sorter: true ,
           render: props => {    //编码转汉字
            return <span>{this.createDictText(props.row.serviceLevel, '2543')}</span>;
          }},
        { title: '事业部', dataIndex: 'deptName', sorter: true },
        { title: '办事处', dataIndex: 'officeName', sorter: true },
        { title: '省份', dataIndex: 'provinceId', sorter: true ,
						render: props => {
							return <span>{this.createRegionText(props.row.provinceId)}</span>;
            }
        },
        { title: '城市', dataIndex: 'cityId', sorter: true ,
						render: props => {
							return <span>{this.createRegionText(props.row.cityId)}</span>;
            }
        },
        { title: '县区', dataIndex: 'districtId', sorter: true ,
						render: props => {
							return <span>{this.createRegionText(props.row.districtId)}</span>;
            }
        },
        { title: '建设地址', dataIndex: 'constructAddress', sorter: true },
        { title: '店端主要联系人', dataIndex: 'dealerLinkman', sorter: true },
        { title: '联系人电话', dataIndex: 'dealerPhone', sorter: true },
        { title: '厂家负责人', dataIndex: 'oemLinkman', sorter: true },
        { title: '负责人电话', dataIndex: 'oemPhone', sorter: true },
        { title: '项目设计师', dataIndex: 'projectDesigner', sorter: true },
        { title: '设计师电话', dataIndex: 'designerPhone', sorter: true },
        { title: '创建人', dataIndex: 'createdByName', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', sorter: true,
          render: props =>{
            return <span>{ formatdateByDay(props.row.createdAt) }</span>
          } }
      ];
    },
    // 人员打开窗口 -传数据
    personnelHandle() {
      this.visiblePersonnel = true;
    },
    // 清空人员数据
    clearPersonnelHandle() {
      //清空数据内容
      this.userId = "";
      this.userName = "";

      //清空人员名称
      this.topFilterInit.find(item => item.fieldName === 'userName').initialValue='';
    },
    // 人员关闭窗口 -返回数据
    closePersonnel(data) {
      if(data.type!="close"&&data.data&&data.data.length>0){
        //清空数据内容
        this.userId = "";
        this.userName = "";

        //循环返回数据
        data.data.forEach(x => {
          //使用逗号分隔拼接用户ID
          if(this.userId==""){
            this.userId = x.userId;
          }else{
            this.userId += "," + x.userId;
          }

          //使用逗号分隔拼接用户姓名
          if(this.userName==""){
            this.userName = x.employeeName;
          }else{
            this.userName += "," + x.employeeName;
          }
        });
        //显示人员名称
        this.topFilterInit.find(item => item.fieldName === 'userName').initialValue = this.userName;
      }
      //关闭弹窗
      this.visiblePersonnel = data.visible; 
    },
    //获取事业部下拉列表数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterInit[3].itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //初始化所在省份
    async initProvince(){
      let pl = this.createRegionList();
      this.topFilterInit[6].itemList = pl;
      // this.initFormBase[19].itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId){
      //清空市
      this.topFilterInit[7].initialValue="";
      //清空县
      this.topFilterInit[8].initialValue="";
      if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      this.topFilterInit[7].itemList = cl;
    },
    //初始化所在县数据
    async initTown(cityId){
      //清空县
      this.topFilterInit[8].initialValue="";
      if(!cityId || cityId==null || typeof(cityId)=='undefined'){
        return;
      }
      let td = this.cityData[cityId].children;
      let tl = this.createSubRegionList(td);
      this.topFilterInit[8].itemList = tl;
    },
    //修改
    dialogHandle(row,type) {
      this.visibleDrawer = true;
      const pram = {
        type: type,
        rowData: row
      };
      this.initData=pram;
    },
    //关闭修改
    dialogClose(data) {
      this.visibleDrawer = false;
      if (data.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    //详情
    dialogHandleShow(row,type) {
      this.visibleDrawerShow = true;
      const pram = {
        type: type,
        rowData: row
      };
      this.initData=pram;
    },
    //关闭详情
    dialogCloseShow(data) {
      this.visibleDrawerShow = false;
      if (data.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //导出
    async exportExcel(){
      this.saveLoading = true;
      // this.$refs.topFilterRef.SUBMIT_FORM();
      this.$refs.topFilterRef.excuteFormData(this.$refs.topFilterRef.form);
      let subForm = this.$refs.topFilterRef.form;
      // exportExcel(this.fetchParams).then(res => {
      exportExcel(subForm).then(res => {
          this.saveLoading = false;
          exportExcelFile(res.data,"建设验收查询");
      });
    }
  }
};
</script>

<style lang="less" scoped>
</style>
